package com.xiaomi.dao.impl;

import com.xiaomi.dao.AddressDao;
import com.xiaomi.entity.Address;
import com.xiaomi.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

/**
 * TODO
 *
 * @author jy
 * @date 2021/5/25
 */
public class AddressDaoImpl implements AddressDao {

    private final QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

    @Override
    public List<Address> showAddressesByUid(int uid) throws Exception {
        String sql = "select * from address where uid=? order by level desc";
        return queryRunner.query(sql, new BeanListHandler<>(Address.class), uid);
    }

    @Override
    public int addAddress(Address address) throws Exception {
        Object[] objects = {address.getUid(), address.getDetail(), address.getName(), address.getPhone(), address.getLevel()};
        String sql = "insert into address values(default,?,?,?,?,?)";
        return queryRunner.update(sql, objects);
    }

    @Override
    public int delete(int aid) throws Exception {
        String sql = "delete from address where aid=?";
        return queryRunner.update(sql, aid);
    }

    @Override
    public int setDefaultByUid(int uid) throws Exception {
        String sql = "update address set level=0 where uid=?";
        return queryRunner.update(sql, uid);
    }

    @Override
    public int setDefaultByAid(int aid) throws Exception {
        String sql = "update address set level=1 where aid=?";
        return queryRunner.update(sql, aid);
    }

    @Override
    public int update(Address address) throws Exception {
        Object[] objects = {address.getName(),address.getPhone(),address.getDetail(),address.getAid()};
        String sql = "update address set name=?,phone=?,detail=? where aid=?";
        return queryRunner.update(sql,objects);
    }


}
